package edu.nf.llmtest.common.sync.impl;

import edu.nf.llmtest.common.converter.UserConverter;
import edu.nf.llmtest.common.enumeration.RedisKeyEnum;
import edu.nf.llmtest.common.sync.DataSyncStrategy;
import edu.nf.llmtest.model.document.UserDoc;
import edu.nf.llmtest.model.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @ Author bin
 * @ Create  2025/10/28 下午8:06
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class UserSyncStrategy implements DataSyncStrategy<User> {
    private final RedisTemplate<String, Object> redisTemplate;

    private final UserConverter userConverter;

    private final ElasticsearchOperations operations;

    @Override
    public boolean supports(Class<?> clazz) {
        return User.class.equals(clazz);
    }

    @Override
    public void syncToRedis(User entity) {
        redisTemplate.opsForValue().set(RedisKeyEnum.USER_EMAIL.getValue() + entity.getEmail(), entity);
        log.info("同步用户到 Redis: {}", entity.getEmail());
    }

    @Override
    public void deleteFromRedis(User entity) {
        redisTemplate.delete(RedisKeyEnum.USER_EMAIL.getValue() + entity.getEmail());
        log.info("从 Redis 删除用户: {}", entity.getEmail());
    }

    @Override
    public void syncToES(User entity) {
        log.info("同步用户到 Elasticsearch: {}", entity.getEmail());
        operations.save(userConverter.convertUserDoc(entity));
    }

    @Override
    public void deleteFromES(User entity) {
        log.info("从 Elasticsearch 删除用户: {}", entity.getEmail());
        operations.delete(entity.getEmail(), UserDoc.class);
    }
}
